package srg

import (
	"encoding/json"
	"time"
)

// 添加队列消息
// 队列消息不支持延迟处理
// 如需延迟消息 可配合延迟消息功能实现
func QueueMsgAdd(queueName string, msgType string, msgTargetId string, msgInfo string) int64 {
	//添加队列消息
	return addQueueMsg(&SrgMsg{
		MsgType:     msgType,
		MsgTargetId: msgTargetId,
		MsgInfo:     msgInfo,
		QueueName:   queueName,
	})
}

// 添加队列消息
// 队列消息不支持延迟处理
// 如需延迟消息 可配合延迟消息功能实现
func addQueueMsg(msg *SrgMsg) int64 {

	msg.Id = GetUniqueId()

	msgBytes, _ := json.Marshal(msg)

	srds.RPush(ctx, queueMsgHead+msg.QueueName, string(msgBytes))

	return msg.Id
}

// 弹出一个消息，转为实时消息
func popQueueMsgByQueueName(queueName string) {

	lock := DLockAdd("pop_one_queue_msg:"+queueName, time.Second*7)
	defer DLockRelease("pop_one_queue_msg:" + queueName)
	if !lock {
		return
	}

	msgBytes, _ := srds.LIndex(ctx, queueName, 0).Result()
	if msgBytes == "" {
		return
	}
	//解析消息
	var msgInfo SrgMsg
	json.Unmarshal([]byte(msgBytes), &msgInfo)

	//查看是否已有该消息
	lockExist, _ := DLockExist("QUEUE_LOCK:" + msgInfo.QueueName)
	if lockExist {
		return
	}

	//转为实时消息
	addMsg(&SrgMsg{
		Id:          msgInfo.Id,
		MsgType:     msgInfo.MsgType,
		MsgTargetId: msgInfo.MsgTargetId,
		MsgInfo:     msgInfo.MsgInfo,
		MsgVer:      msgInfo.MsgVer,
		QueueName:   msgInfo.QueueName,
		TiggerTime:  time.Now().UnixMilli(),
	})

	//设置队列锁
	DLockAdd("QUEUE_LOCK:"+msgInfo.QueueName, 0)
	//删除队列消息
	srds.LPop(ctx, queueName)
}

// 弹出一个消息，转为实时消息
func popQueueMsg() {

	queueKeys, _ := srds.Keys(ctx, queueMsgHead+"*").Result()

	for _, queueKey := range queueKeys {
		popQueueMsgByQueueName(queueKey)
	}
}
